package com.kevin.proxy.dynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class InterceptorProxy implements InvocationHandler {
    private  Object target;
    private  String intercepterName;

    public InterceptorProxy() {
    }

    public InterceptorProxy(Object target, String intercepterName) {
        this.target = target;
        this.intercepterName = intercepterName;
    }

    public  Object bind(Object target, String intercepterName){
        this.target = target;
        this.intercepterName = intercepterName;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new InterceptorProxy(target,intercepterName)/*这个参数是责任链的关键*/);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        Interceptor interceptor = (Interceptor) Class.forName(intercepterName).newInstance();
        if (interceptor == null) {
            result = method.invoke(target, args);
        }else{
            interceptor.before(proxy,method,args,target);
            result = method.invoke(target,args);
            interceptor.after(proxy,method,args,target);
        }
        return result;
    }
}
